package com.jee.ssm.common.utils.mq.jms;

import javax.jms.Session;  
import javax.jms.Topic;  
import javax.jms.TopicConnection;  
import javax.jms.TopicConnectionFactory;  
import javax.jms.TopicSession;  
import javax.jms.TopicSubscriber;  
import javax.naming.Context;  
import javax.naming.InitialContext;

public class SimpleSubscriber {
	
	private TopicConnection connection;  
    private TopicSession session;  
    private TopicSubscriber consumer;  
      
    private boolean isStarted;  
      
    public SimpleSubscriber(String clientId) throws Exception{  
        Context context = new InitialContext();  
        TopicConnectionFactory connectionFactory = (TopicConnectionFactory)context.lookup("TopicCF");  
        connection = connectionFactory.createTopicConnection();  
        connection.setClientID(clientId);  
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);  
        Topic topic = (Topic)context.lookup("topic1");  
        consumer = session.createDurableSubscriber(topic, "Test-subscriber");  
        consumer.setMessageListener(new TopicMessageListener());  
    }  
      
      
    public synchronized boolean start(){  
        if(isStarted){  
            return true;  
        }  
        try{  
            connection.start();  
            isStarted = true;  
            return true;  
        }catch(Exception e){  
            return false;  
        }  
    }  
      
    public synchronized void close(){  
        isStarted = false;  
        try{  
            session.close();  
            connection.close();  
        }catch(Exception e){  
            //  
        }  
    }  

}
